local desc_fan_dragon = [[
  # 斩首行动简介

  ---
  说明：斩首模式：4明反+3忠1主
  规则：明反杀死主公即为胜利，每轮开始时主公会重新复活死亡的忠臣

]]

local vanished_dragon_getLogic = function()
  local vanished_dragon_logic = GameLogic:subclass("jbsfan_dragon_logic")

  function vanished_dragon_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {nil, nil, nil, nil, nil, 
    {"hidden", "loyalist", "rebel", "rebel", "rebel","loyalist"},
    {"hidden", "loyalist", "loyalist", "rebel", "rebel", "rebel", "loyalist"}, 
    {"hidden", "loyalist", "loyalist", "rebel", "rebel", "rebel", "rebel", "loyalist"} }
  end

  function vanished_dragon_logic:assignRoles()
    local room = self.room
    local players = room.players
    local n = #players
    local roles = self.role_table[n]
    table.shuffle(roles)

    room:setTag("ShownLoyalist", nil)
    room:setTag("Shownlord", nil)
    for i = 1, n do
      local p = players[i]
      p.role = roles[i]
     
        if p.role~="rebel" and not room:getTag("ShownLoyalist") then
          room:notifyProperty(p, p, "role")
          room:setTag("ShownLoyalist", p.id)
          room:setTag("Shownlord", p.role)

          p.role = "lord"
        elseif p.role=="rebel" then
          p.role_shown = true
          room:broadcastProperty(p, "role")
        else
          room:notifyProperty(p, p, "role")

      end
    end
  end


  function vanished_dragon_logic:chooseGenerals()
    local room = self.room
    local generalNum = room:getSettings('generalNum')
    local n = room:getSettings('enableDeputy') and 2 or 1
    local lord = room:getLord()
    room.current = lord
    lord.role =  room:getTag("Shownlord")
    for _, p in ipairs(room.players) do
      if p.role == "hidden" then
        p.role = "lord"
        room:notifyProperty(p, p, "role")
      end

    end

    for _, p in ipairs(room.players) do
      if p.role~="rebel" then
        room:notifyProperty(p, room:getLord(), "role")
      end

    end

    room:doBroadcastNotify("ShowToast", "<b>" .. lord._splayer:getScreenName() .. "</b>" .. Fk:translate("jbs_intro"))

    local lord_generals = {}

    if lord ~= nil then
      local generals = {}
      local lordlist = {}
      local lordpools = {}
      table.insertTable(generals, Fk:getGeneralsRandomly(generalNum, Fk:getAllGenerals(), table.map(generals, function (g)
        return g.name
      end)))
      for _, general in ipairs({"cuiyan", "ty__huangfusong"}) do
        if not table.contains(room.disabled_packs, Fk.generals[general].package.name) and
          not table.contains(room.disabled_generals, general) and not table.find(generals, function(g)
            return g.trueName == "cuiyan" or g.trueName == "huangfusong"
          end) then
          table.insert(lordlist, general)
        end
      end
      for i = 1, #generals do
        generals[i] = generals[i].name
      end
      lordpools = table.simpleClone(generals)
      table.insertTable(lordpools, lordlist)
      lord_generals = room:askForGeneral(lord, lordpools, n)
      local lord_general, deputy
      if type(lord_generals) == "table" then
        deputy = lord_generals[2]
        lord_general = lord_generals[1]
      else
        lord_general = lord_generals
        lord_generals = {lord_general}
      end

      room:setPlayerGeneral(lord, lord_general, true)
      room:askForChooseKingdom({lord})
      room:broadcastProperty(lord, "general")
      room:broadcastProperty(lord, "kingdom")
      room:setDeputyGeneral(lord, deputy)
      room:broadcastProperty(lord, "deputyGeneral")
    end

    local nonlord = room:getOtherPlayers(lord, true)
    local generals = Fk:getGeneralsRandomly(#nonlord * generalNum, nil, lord_generals)
    table.shuffle(generals)
    for _, p in ipairs(nonlord) do
      local arg = {}
      for i = 1, generalNum do
        table.insert(arg, table.remove(generals, 1).name)
      end
      p.request_data = json.encode{ arg, n }
      p.default_reply = table.random(arg, n)
    end

    room:notifyMoveFocus(nonlord, "AskForGeneral")
    room:doBroadcastRequest("AskForGeneral", nonlord)

    for _, p in ipairs(nonlord) do
      if p.general == "" and p.reply_ready then
        local generals = json.decode(p.client_reply)
        local general = generals[1]
        local deputy = generals[2]
        room:setPlayerGeneral(p, general, true, true)
        room:setDeputyGeneral(p, deputy)
      else
        room:setPlayerGeneral(p, p.default_reply[1], true, true)
        room:setDeputyGeneral(p, p.default_reply[2])
      end
      p.default_reply = ""
    end

    room:askForChooseKingdom(nonlord)
  end

  function vanished_dragon_logic:broadcastGeneral()
    local room = self.room
    local players = room.players
    local lord = room:getTag("ShownLoyalist")

    for _, p in ipairs(players) do
      assert(p.general ~= "")
      local general = Fk.generals[p.general]
      local deputy = Fk.generals[p.deputyGeneral]
      p.maxHp = deputy and math.floor((deputy.maxHp + general.maxHp) / 2)
        or general.maxHp
      p.hp = deputy and math.floor((deputy.hp + general.hp) / 2) or general.hp
      p.shield = math.min(general.shield + (deputy and deputy.shield or 0), 5)
      -- TODO: setup AI here

      if p.id ~= lord then
        room:broadcastProperty(p, "general")
        room:broadcastProperty(p, "kingdom")
        room:broadcastProperty(p, "deputyGeneral")
      end
      if p.role=="rebel" then
        room:broadcastProperty(p, "role")
      elseif #players >= 5 then
        p.maxHp = p.maxHp + 1
        p.hp = p.hp + 1
      end
      room:broadcastProperty(p, "maxHp")
      room:broadcastProperty(p, "hp")
      room:broadcastProperty(p, "shield")
    end
  end

  function vanished_dragon_logic:attachSkillToPlayers()
    local room = self.room
    local players = room.players
    local lord = room:getTag("ShownLoyalist")
  
    local addRoleModSkills = function(player, skillName)
      local skill = Fk.skills[skillName]
      if skill.lordSkill then
        return
      end
  
      if #skill.attachedKingdom > 0 and not table.contains(skill.attachedKingdom, player.kingdom) then
        return
      end
  
      room:handleAddLoseSkills(player, skillName, nil, false)
    end
    for _, p in ipairs(room.alive_players) do
      local skills = Fk.generals[p.general].skills
      for _, s in ipairs(skills) do
        addRoleModSkills(p, s.name)
      end
      for _, sname in ipairs(Fk.generals[p.general].other_skills) do
        addRoleModSkills(p, sname)
      end
  
      local deputy = Fk.generals[p.deputyGeneral]
      if deputy then
        skills = deputy.skills
        for _, s in ipairs(skills) do
          addRoleModSkills(p, s.name)
        end
        for _, sname in ipairs(deputy.other_skills) do
          addRoleModSkills(p, sname)
        end
      end

    end
  end

  return vanished_dragon_logic
end

--明主杀暗忠呢
---@param killer ServerPlayer
local function rewardAndPunish(killer, victim, room)
  if killer.dead then return end
  local shownLoyalist = room:getTag("ShownLoyalist")
  if (victim.id == shownLoyalist and killer.role == "lord") or (victim.role == "loyalist" and killer.id == shownLoyalist) then
    killer:throwAllCards("he")
  elseif victim.role == "rebel" or victim.id == shownLoyalist then
    killer:drawCards(3, "kill")
  end
end

local vanished_dragon_rule = fk.CreateTriggerSkill{
  name = "#jbsfan_dragon_rule",
  priority = 0.001,
  refresh_events = {fk.GameStart,fk.RoundStart},
  can_refresh = function(self, event, target, player, data)
    local room = player.room
    
    if target ~= player then return false end
    return true
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      room:setTag("SkipNormalDeathProcess", true)
    elseif event==fk.RoundStart then
      for _, p in ipairs(room.players) do
        if p.role=="loyalist" then
          room:revivePlayer(p, false)
          p:drawCards(4)

        end
      end
   end
  end,
}

local vanished_dragon = fk.CreateGameMode{
  name = "jbsfan_dragon",
  minPlayer = 6,
  maxPlayer = 8,
  rule = vanished_dragon_rule,
  logic = vanished_dragon_getLogic,
}



Fk:loadTranslationTable{
  ["jbsfan_dragon"] = "斩首行动",
  [":jbsfan_dragon"] = desc_fan_dragon,

  ["jbs_intro"] = "是<b>未知身份</b>，<b>开始选将</b><br>场上目前反贼4人！找到潜伏的主公并杀掉他！否则每轮开始主公会复活死亡的忠臣！",

}

return vanished_dragon
